package com.njupt.towerssystem.services.impl;

import com.njupt.towerssystem.domain.ManageInfos;
import com.njupt.towerssystem.mapper.ManageInfoMapper;
import com.njupt.towerssystem.services.ManageService;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Random;
import java.util.UUID;

@Service
//@Scope("prototype") //原型模式
public class ManageServiceImpl implements ManageService {
//    @Resource
//    private ManageInfoMapper manageInfoMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ManageInfos login(String loginname, String loginpwd, String token) {

        if(loginname!=null) {
            Object res = stringRedisTemplate
                    .opsForHash().get("manages", loginname+loginpwd);
            if(res!=null){
                //生成唯一令牌
                String tk = UUID.randomUUID().toString().replaceAll("-", "");
                //将令牌存放到redis数据库中 让令牌保存30秒
                stringRedisTemplate.opsForValue()
                        .set(tk,loginname+loginpwd, Duration.ofMinutes(30+ (int)(Math.random()*100)));
                //找到对应用户
                String[] infos = res.toString().split(",");
                ManageInfos mis = ManageInfos.builder()
                        .userid(Integer.parseInt(infos[0]))
                        .username(infos[1])
                        .loginname(infos[2])
                        .loginpwd(infos[3])
                        .tel(infos[4])
                        .department(infos[5])
                        .token(tk)
                        .build();
                return mis;
            }else{
                //找不到对应用户
                return null;
            }


        }else{
            //验证用户传入的token 查看是否存在 //loginname+loginpwd
            String res = stringRedisTemplate.opsForValue()
                    .get(token);
            if(res!=null){
                //令牌存在 按照令牌的key取loginname和loginpwd
                Object obj = stringRedisTemplate.opsForHash()
                        .get("manages", res);
                String[] infos = obj.toString().split(",");
                ManageInfos mis = ManageInfos.builder()
                        .userid(Integer.parseInt(infos[0]))
                        .username(infos[1])
                        .loginname(infos[2])
                        .loginpwd(infos[3])
                        .tel(infos[4])
                        .department(infos[5])
                        .token(token)
                        .build();
                return mis;
            }
            return null;
        }
    }
}
